If statement is used to execute a statement or block, if, and only if, a condition is true.
General syntax:
if ( a condition is true )
{
Execute all statements inside the braces
}
else
{
Execute all statements inside the braces if the condition is not true
}
Practical example 1:
#include <iostream>
int main()
{
int number = 0;
std::cout << "Please enter a number bigger than 100: " << std::endl;
std::cin >> number;
if(number > 100)
{
std::cout << "The number is bigger than 100. " << std::endl;
}
else
{
std::cout << "The number " << number << " is not bigger than 100." << std::endl;
}
}
The example above showed an if-else statement. If the condition between the parenthesis is false, the code execution jumps directly to the else branch.
Practical example 2:
#include <iostream>
int main()
{
int number = 0;
std::cout << "Please enter the number 100: " << std::endl;
std::cin >> number;
if(number < 100)
{
std::cout << "The number is lower than 100. " << std::endl;
}
else if(number == 100)
{
std::cout << "Congrats!" << std::endl;
}
else if(number > 100)
{
std::cout << "The number is bigger than 100." << std::endl;
}
else
{
std::cout << "Please enter the number 100!" << std::endl;
}
}
This example shows the if-else if-else conditional structure where one can check multiple cases.